<?php

include "DBConnect.class.php";

class GThaiParser{
  private $id;
  private $link;
  private $reference;
  private $icon;

  /**
   * Constructure
   * @param attri $link - contains xml link.
   * @param attri $referrence - contains host of xml.
   * @param attri $icon - icon link.
   */
  public function __construct ($id){
    $this->id = $id;
    $this->init();
  }
  
  public function xmlReader(){
    $xmlDoc = new DOMDocument('1.0', 'UTF-8');
    $xmlDoc->load($this->link);

    $channel = $xmlDoc->getElementsByTagName('channel')->item(0);
    $channel_title = $channel->getElementsByTagName('title')->item(0)->childNodes->item(
    0)->nodeValue;
    $channel_link = $channel->getElementsByTagName('link')->item(0)->childNodes->item(
    0)->nodeValue;
    $channel_desc = $channel->getElementsByTagName('description')->item(
    0)->childNodes->item(0)->nodeValue;
    $x = $xmlDoc->getElementsByTagName('item');
    $i = 0;
    
    foreach ($xmlDoc->getElementsByTagNameNS('http://www.georss.org/georss', 'point') as $element){
      $item_title = $x->item($i)
        ->getElementsByTagName('title')
        ->item(0)->childNodes->item(0)->nodeValue;

      $item_desc = $this->html2txt(
      $x->item($i)
        ->getElementsByTagName('description')
        ->item(0)->childNodes->item(0)->nodeValue);
      $item_date = $x->item($i)
        ->getElementsByTagName('pubDate')
        ->item(0)->childNodes->item(0)->nodeValue;
      $item_lat_lon = $element->nodeValue;
      $expladLatLon = explode(" ", trim($item_lat_lon));
      $lat = $expladLatLon[0];
      $lon = $expladLatLon[1];
      
      $result['layer'][$i]['title'] = $item_title;
      $result['layer'][$i]['description'] = $this->reference;
      $result['layer'][$i]['icon'] = $this->icon;
      $result['layer'][$i]['detail'] = $item_desc;
      $result['layer'][$i]['latitude'] = $lat;
      $result['layer'][$i]['longitude'] = $lon;
      
      $i ++;
    }
    return $result;
  }
  
  public function xmlWriter(){    
  }
  
  private function init(){
    
    foreach (DBConnect::query(
      "SELECT layer.name AS reference ,layer.icon AS icon,layer.link AS link FROM gthai.gthai_layer AS layer WHERE layer.id = $this->id") as $result)
      {
      $this->link = $result['link'];
      $this->reference = $result['referrence'];
      $this->icon = $result['icon'];
      }
  }
  
  private function html2txt ($document){
    $search = array(
      '@<script[^>]*?>.*?</script>@si', // Strip out javascript 
'@<[\/\!]*?[^<>]*?>@si',  // Strip out HTML tags 
    '@<style[^>]*?>.*?</style>@siU', // Strip style tags properly 
'@<![\s\S]*?--[ \t\n\r]*>@' // Strip multi-line comments including CDATA 
    );
    $text = preg_replace($search, '', $document);
    return $text;
  }
}
?>